package com.duoketech.interceptor;

import com.duoketech.config.Constant;
import com.duoketech.model.member.Member;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.net.URLEncoder;

public class MemberInterceptor implements Interceptor {
    @Override
    public void intercept(Invocation invocation) {

        Controller c = invocation.getController();
        String returnUrl = getCurrentUrl(c);
        int memberId = c.getCookieToInt(Constant.MEMBER_SHOP_COOKIE_NAME,0);
        if(memberId>0){
            Member member= Member.dao.findById(memberId);
            int role = member.getInt(Member.ROLE);
            if(role<=0){
                c.renderText("【温馨提示】：你暂时没有权限访问当前系统，请联系管理员开启相关权限");
            }else{
                c.setAttr("member",member);
                invocation.invoke();
            }
        }else{
            if(StringUtils.isNotEmpty(returnUrl)){
                returnUrl = URLEncoder.encode(returnUrl);
                c.redirect("/travel/login?returnUrl="+returnUrl);
            }else{
                c.redirect("/travel/login");
            }

        }

    }


    public String getCurrentUrl(Controller c){
        HttpServletRequest request = c.getRequest();
        String url = request.getRequestURI();
        String scheme = request.getScheme();
        String serverName = request.getServerName();
        String queryString = request.getQueryString();
        url = (queryString==null)?scheme+"://"+serverName+url:scheme+"://"+serverName+url+"?"+queryString;
        System.out.println(url);
        return url;
    }
}
